package judesart.app.client.ui.pub.exhibition;

import java.util.List;

import judesart.app.client.controller.ExhibitionController;
import judesart.app.client.controller.ExhibitionControllerAsync;
import judesart.app.client.ui.pub.layout.PublicMainLayout;
import judesart.app.domain.Address;
import judesart.app.domain.Exhibition;
import judesart.app.domain.User;

import com.allen_sauer.gwt.log.client.Log;
import com.extjs.gxt.ui.client.data.BaseListLoader;
import com.extjs.gxt.ui.client.data.BeanModel;
import com.extjs.gxt.ui.client.data.BeanModelReader;
import com.extjs.gxt.ui.client.data.ListLoadResult;
import com.extjs.gxt.ui.client.data.ListLoader;
import com.extjs.gxt.ui.client.data.LoadEvent;
import com.extjs.gxt.ui.client.data.RpcProxy;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.LoadListener;
import com.extjs.gxt.ui.client.event.SelectionChangedEvent;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.widget.Composite;
import com.extjs.gxt.ui.client.widget.Html;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.ListView;
import com.extjs.gxt.ui.client.widget.layout.ColumnData;
import com.extjs.gxt.ui.client.widget.layout.ColumnLayout;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.rpc.AsyncCallback;

public class PubExhibitionsPanel extends Composite {

    private static final DateTimeFormat formater = DateTimeFormat.getFormat("EEE, MMMM dd, yyyy");

    private final ExhibitionControllerAsync exhibitionController = ExhibitionController.Util.getInstance();
    private final LayoutContainer mainPanel;
    private final ListView<BeanModel> listViewExhibitions;
    private final ListLoader<ListLoadResult<Exhibition>> loader;
    private User user;

    public PubExhibitionsPanel() {
        mainPanel = new LayoutContainer();
        mainPanel.setWidth(900);
        mainPanel.setStyleAttribute("min-height", "600px");
        mainPanel.setBorders(false);
        mainPanel.setId("id-jaw-PubExbitionsPanel");
        mainPanel.setLayout(new ColumnLayout());

        Html htmlTitle = new Html();
        htmlTitle.setTagName("h1");
        htmlTitle.setId("id-jaw-PubExbitionsPanel-title");
        htmlTitle.setHtml("Exhibitions");
        mainPanel.add(htmlTitle, new ColumnData(.33));

        RpcProxy<List<Exhibition>> proxy = new RpcProxy<List<Exhibition>>() {
            @Override
            protected void load(Object loadConfig,
                    final AsyncCallback<List<Exhibition>> callback) {
                Log.debug(" > Load exhibitions");
                getExhibitions(callback);
            }
        };

        loader = new BaseListLoader<ListLoadResult<Exhibition>>(proxy, new BeanModelReader());
        loader.addLoadListener(new LoadListener(){
        	@Override
        	public void loaderLoad(LoadEvent le) {
        		onLoadCompleted(le);
        	}
        });
        ListStore<BeanModel> store = new ListStore<BeanModel>(loader);

        listViewExhibitions = new ListView<BeanModel>(store) {
            @Override
            protected BeanModel prepareData(BeanModel model) {
                loadPrepareData(model);
                return model;
            }
        };
        listViewExhibitions.setLoadingText("loading...");
        listViewExhibitions.setBorders(false);
        listViewExhibitions.setWidth(800);
        listViewExhibitions.setTemplate(getTemplate());
        listViewExhibitions.setItemSelector("div.thumb-wrap");
        listViewExhibitions.getSelectionModel().addListener(
                Events.SelectionChange,
                new Listener<SelectionChangedEvent<BeanModel>>() {
                    public void handleEvent(SelectionChangedEvent<BeanModel> be) {
                        onSelectionChanged(be);
                    }
                });
        listViewExhibitions.setId("id-jaw-PubExhibitionsPanel-list");
        mainPanel.add(listViewExhibitions, new ColumnData(.66));

        initComponent(mainPanel);
    }
    
    private void onLoadCompleted(LoadEvent le){
    	PublicMainLayout.getInstance().loading(false);
    }

    public void setUser(User user) {
        Log.debug(" > setUser");
        this.user = user;
    }

    public void list() {
        loader.load();
        mainPanel.layout();
    }

    private void getExhibitions(final AsyncCallback<List<Exhibition>> callback) {
        exhibitionController.findAllUserExhibitions(this.user.getId(), callback);
    }

    private BeanModel loadPrepareData(BeanModel model) {
        Exhibition e = model.getBean();
        if (e.getStartDate() != null)
            model.set("startDateFormated", formater.format(e.getStartDate()));
        if (e.getEndDate() != null)
            model.set("endDateFormated", formater.format(e.getEndDate()));
        if (e.getPhotos() != null && e.getPhotos().size() > 0)
            model.set("photoId", e.getPhotos().get(0).getImageId().toString());
        Address address = e.getGalleryAddress();
        if (address != null && address.getCity() != null
                && address.getCity().trim().length() > 0
                && address.getCountry() != null) {
            model.set("location", address.getCity() + ", "
                    + address.getCountry().title());
        }
        return model;
    }

    private void onSelectionChanged(SelectionChangedEvent<BeanModel> be) {
        Object source = be.getSource();
        Log.debug("source [" + source + "]");
        if (be.getSelection().size() == 0) {
            return;
        }
        final BeanModel model = be.getSelection().get(0);
        Exhibition exhibition = model.getBean();
        History.newItem("exhibition/" + exhibition.getId());
    }

    private native String getTemplate() /*-{
        return ['<tpl for=".">', 
        '<div class="thumb-wrap" id="{id}">', 
        '<span class="thumb"><img src="/image/{photoId}_120x120" title="{title}"/></span>',
        '<span class="thumb-legend">',
        '<span class="dates">{startDateFormated} - {endDateFormated}</span>',
        '<span class="location">{location}</span>',
        '<span class="title">{title}</span>',
        '</span>', 
        '<div class="x-clear"></div>',
        '</div>',
        '</tpl>', 
        '<div class="x-clear"></div>'].join("");
    }-*/;
}
